<?php
$host = "localhost";   // Host name
$username = "root";    // MySQL username
$password = "";        // MySQL pass
$db_name = "okul";     // DB name
$tb_name = "user";     // Table name

// Connect to server and select DB
mysql_connect("$host", "$username", "$password") or die("Cannot connect to SQL Server");
mysql_select_db("$db_name") or die("cannot select DB");

// student email and ID sent from form
$stemail = $_POST['email'];
$stid = $_POST['studentID'];


// to protect MySQL injection
$stemail = stripslashes($stemail);
$stid = stripslashes($stid);
$stemail = mysql_real_escape_string($stemail);
$stid = mysql_real_escape_string($stid);

$sql_select1 = "SELECT email, st_id, issaved FROM User WHERE(st_id = '$stid')";
$sql_select2 = "SELECT st_id FROM User WHERE(email = '$stemail')";
$result1 = mysql_query($sql_select1);
$result2 = mysql_query($sql_select2);

$row = mysql_fetch_array($result1);
$count1 = mysql_num_rows($result1);
$count2 = mysql_num_rows($result2);

if ($count1 == 0 && $count2 == 1){
    echo "You entered wrong email!";
} else if ($count1 == 0 && $count2 == 0){
   $sql = "INSERT INTO User(email, st_id) VALUES('$stemail', '$stid')";
    mysql_query($sql);
    mysql_close($sql);
    
    session_start();
    // Register $stemail, $stid and redirect to file login_success.php
    $_SESSION['stid'] = $_POST['studentID'];
    header("location:index.php");

    ob_end_flush();
}else if($count1 == 1) {
    if($row['email'] == $stemail) {
    session_start();
    // Register $stemail, $stid and redirect to file login_success.php
    $_SESSION['stid'] = $_POST['studentID'];
    header("location:index.php");

    ob_end_flush();
    } else {
        echo "You entered wrong email!";
    }
} else if($row['email'] == $stemail && $row['issaved'] == 1) {
    session_start();
    // Register $stemail, $stid and redirect to file login_success.php
    $_SESSION['stid'] = $_POST['studentID'];
    header("location:index.php");
} else if($row['email'] == $stemail && $row['issaved'] == 0){
        echo "You cannot fill application form any more!";
}

?>